package com.jwong.grpc.jwtauth;

import com.jwong.grpc.helloworld.GreeterGrpc;
import com.jwong.grpc.helloworld.HelloReply;
import com.jwong.grpc.helloworld.HelloRequest;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * 管理 Greeter 服务器的启动关闭的服务器。这也使用了 JwtServerInterceptor 来拦截传递的 JWT 令牌
 */
public class AuthServer {

  private static final Logger logger = Logger.getLogger(AuthServer.class.getName());

  private Server server;
  private int port;

  public AuthServer(int port) {
    this.port = port;
  }

  private void start() throws IOException {
    server = ServerBuilder.forPort(port)
        .addService(new GreeterImpl())
        .intercept(new JwtServerInterceptor())  // 添加 JwtServerInterceptor
        .build()
        .start();
    logger.info("Server started, listening on " + port);
    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        // 在此处使用 stderr，因为记录器可能已被其 JVM ShutdownHook重置。
        System.err.println("*** shutting down gRPC server since JVM is shutting down");
        AuthServer.this.stop();
        System.err.println("*** server shut down");
      }
    });
  }

  private void stop() {
    if (server != null) {
      server.shutdown();
    }
  }

  /**
   * 由于 grpc 库使用守护线程，因此在主线程上等待终止。
   */
  private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
      server.awaitTermination();
    }
  }

  /**
   * Main 从命令行启动服务器。
   */
  public static void main(String[] args) throws IOException, InterruptedException {

    // 服务器应该运行的端口
    int port = 9000;
    final AuthServer server = new AuthServer(port);
    server.start();
    server.blockUntilShutdown();
  }

  static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
    @Override
    public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
      // 获取通过拦截器添加到上下文的客户端 ID
      String clientId = Constant.CLIENT_ID_CONTEXT_KEY.get();
      logger.info("Processing request from " + clientId);
      HelloReply reply = HelloReply.newBuilder().setMessage("Hello, " + req.getName()).build();
      responseObserver.onNext(reply);
      responseObserver.onCompleted();
    }
  }
}
